import React, { Component } from 'react'
import TextAreaWidget from '@/components/basicWidget/TextAreaWidget'
import { CloseOutlined, CloseSquareOutlined } from '@ant-design/icons'
import Button from '@/components/basicWidget/Button'

import './index.css'
import { commonQueryByCode } from '@/service/document/documentService'
import { Spin, message, Modal } from 'antd'
import { _delete, put } from '@/utils/requestUtil'
import Avatar from '../Avatar'

const { confirm } = Modal

/**
 * 评论遮盖
 * @author liu_jshan
 * @version 1.0 20240324
 * 
 * visual: 显隐 boolean
 * onCancel: 隐藏函数 function()
 * blogId：博客id string
 * blogAuthorId: 博客作者id
 * user: 当前登录用户 object             
 */
class CommentsMasked extends Component {

    constructor(props) {
        super(props)
        this.state = {
            loading: true,
            comments: [],
            commentValue: '',
            replyCustomerId: '', //要回复的对象的id
            replyNickname: '', //要回复的对象的昵称
            textAreaKey: new Date().getTime() + ''
        }
    }

    async componentDidMount() {
        let blogId = this.props.blogId
        let comments = []
        if (blogId) {
            comments = await getCommentsByBlogId(blogId, this.props.user.id)
        }
        await new Promise(resolve => {
            this.setState({
                comments,
                loading: false
            }, resolve)
        })
    }

    //发布评论
    leaveComment = async () => {
        if (!this.state.commentValue) {
            message.warning('评论内容不能为空')
            return false
        }
        //组装数据
        let comment = {
            text: this.state.commentValue,
            customerId: this.props.user.id,
            blogId: this.props.blogId,
            replyCustomerId: this.state.replyCustomerId
        }
        const response = await put('/blog/comment/leave', {
            body: JSON.stringify(comment)
        })
        if (response && response.data === true) {
            message.success('评论发布成功')
            let comments = await getCommentsByBlogId(this.props.blogId, this.props.user.id)
            await new Promise(resolve => {
                this.setState({
                    commentValue: '',
                    textAreaKey: new Date().getTime() + '',
                    replyCustomerId: '',
                    replyNickname: '',
                    comments
                }, resolve)
            })
        }
    }

    //删除评论
    deleteComment = async (id, nickname) => {
        confirm({
            content: `确定要删除 ${nickname} 的评论吗`,
            onOk: async () => {
                const response = await _delete(`/blog/comment/${id}/delete`)
                if (response && response.data === true) {
                    message.success('评论删除成功')
                    let comments = await getCommentsByBlogId(this.props.blogId, this.props.user.id)
                    await new Promise(resolve => {
                        this.setState({
                            comments
                        }, resolve)
                    })
                }
            },
            onCancle: async () => {
                return
            }
        })
    }

    render() {
        if (this.state.loading === true) return <Spin />
        return (
            <div
                className={this.props.visual === true ? 'CommentsMasked-show' : 'CommentsMasked-none'}
            >
                <div className='CommentsMasked-covers'
                    onClick={async () => {
                        if (this.props.onCancel && typeof this.props.onCancel === 'function') {
                            await this.props.onCancel()
                        }
                    }}
                >
                </div>
                <div className='CommentsMasked-main'>
                    <div className='CommentsMasked-header'>
                        <span>评论{this.state.comments.length > 0 ? this.state.comments.length : ''}</span>
                        <CloseOutlined
                            style={{ cursor: 'pointer', float: 'right' }}
                            onClick={async () => {
                                if (this.props.onCancel && typeof this.props.onCancel === 'function') {
                                    await this.props.onCancel()
                                }
                            }}
                        />
                    </div>
                    <div className='CommentsMasked-body'>
                        <CommentAvatar src={this.props.user.avatarUrl}></CommentAvatar>
                        <div className='CommentsMasked-write'>
                            {
                                this.state.replyCustomerId ?
                                    <div className='CommentsMasked-write-reply'>
                                        <span>@ {this.state.replyNickname}</span>
                                        <CloseSquareOutlined
                                            style={{ float: 'right', cursor: 'pointer' }}
                                            onClick={async () => {
                                                await new Promise(resolve => {
                                                    this.setState({
                                                        replyCustomerId: '',
                                                        replyNickname: ''
                                                    }, resolve)
                                                })
                                            }}
                                        />
                                    </div> : ''
                            }
                            <TextAreaWidget
                                key={this.state.textAreaKey}
                                resize={false}
                                rows={5}
                                placeholder='说点什么吧'
                                value={this.state.commentValue}
                                onChange={async (value) => {
                                    await new Promise(resolve => {
                                        this.setState({ commentValue: value }, resolve)
                                    })
                                }}
                            ></TextAreaWidget>
                            <Button
                                onClick={this.leaveComment}
                            >评论</Button>
                        </div>
                    </div>
                    <div className='CommentsMasked-comments'>
                        {
                            this.state.comments.map(item => {
                                return (
                                    <div className='CommentsMasked-comments-item' key={item.id}>
                                        <CommentAvatar src={item.avatarUrl}></CommentAvatar>
                                        <div className='CommentsMasked-comments-item-content'>
                                            <div>
                                                <span>{item.nickname}{item.replyNickname ? ' 回复 ' + item.replyNickname : ''}{' ' + item.createTime}</span>
                                                <span style={{ float: 'right' }}>
                                                    <span
                                                        style={{ cursor: 'pointer', padding: '0 5px' }}
                                                        onClick={async () => {
                                                            await new Promise(resolve => {
                                                                this.setState({
                                                                    replyCustomerId: item.customerId,
                                                                    replyNickname: item.nickname
                                                                }, resolve)
                                                            })
                                                        }}
                                                    >回复</span>
                                                    {
                                                        this.props.user.id === item.customerId || this.props.user.id === this.props.blogAuthorId ?
                                                            <span
                                                                style={{ cursor: 'pointer', padding: '0 5px' }}
                                                                onClick={async () => {
                                                                    await this.deleteComment(item.id, item.nickname)
                                                                }}
                                                            >删除</span> : ''
                                                    }
                                                </span>
                                            </div>
                                            <div style={{ lineHeight: '1.8em' }}>{item.text}</div>
                                        </div>
                                    </div>
                                )
                            })
                        }
                    </div>
                </div>
            </div>
        )
    }
}

export default CommentsMasked

function CommentAvatar(props) {
    return <Avatar
        {...props}
        isCircle={true}
        style={{ width: '40px', height: '40px', marginTop: '10px' }}
    />
}

/**
 * 根据博客id查询博客评论
 * @param {String} blogId 博客id
 * @param {String} userId 当前用户id
 */
export async function getCommentsByBlogId(blogId, userId) {
    let comments = []
    const response = await commonQueryByCode({
        commandCode: 'getCommentsByBlogId',
        kvMap: {
            blogId,
            userId
        }
    })
    if (response && response.code === 200) {
        comments = response.data.documents.map(item => {
            return item.content
        })
    }
    return comments
}